import React, { useEffect, useState, useRef } from 'react';
import jsMind from '@/utils/js.mind';
import menuDefine from '@/utils/jsmind.menu';
import { renderMind, options, remove_current_node, projectStyle, renderEnvStyle, branchStyle, nameStyle, storyStyle } from '@/utils/config/mindConfig';
import { Button, message, Radio, Space, Modal } from 'antd';
import PageTitle from '@/components/pageTitle';
import { useHeight } from '@/utils/hooks/height';
import { searchApi } from '@/request/gitlab';
import { getSystemApi } from '@/request/system';
import { deleteMergeBranchApi, getListApi, getMergeBranchListApi, moveBranchApi } from '@/request/mind';
import MyModal from '@/components/modal';
import { tapdUrl, env } from '@/utils/data';
import MergeBranch from './components/modal';
import Search from './components/search';

interface storyWithProjectItem {
  env: string;
  project_id: string | number;
  branch: string;
  story_id: string;
  developer: string | string[];
  _id: string;
  type: number;
  story_name: string;
}

interface projectItem {
  _id: string;
  envs: string[];
  id: string;
  [key: string]: any;
}

let m = null;

const Mind = () => {
  const jm: any = useRef(null);
  const mergeBranchModal: any = useRef<any>(null);
  const [mergeBranchList, setMergeBranchList] = useState<string[]>([]);
  const [mergeBranch, setMergeBranch] = useState<string>('');
  const [openDialog, setOpenDialog] = useState<boolean>(false);
  const [selectNode, setSelectNode] = useState<any>();
  const { height } = useHeight(181);
  const [projectOption, setProjectOption] = useState<any[]>([]);
  const treeData = useRef<any>();

  // 3、所有项目 生成6个环境
  const envs2 = (projects: projectItem[]) => {
    const arr: any = [];
    for (let i = 0; i < projects.length; i += 1) {
      const { name, envs: projectEnv, id, position, _id } = projects[i];
      const item: any = {
        id: _id,
        topic: name,
        parentid: 'root',
        direction: position,
        props: {
          project_id: id,
          project_name: name,
          level: 2,
        },
        ...projectStyle,
      };
      arr.push(item);
      for (let j = 0; j < projectEnv.length; j += 1) {
        const envItem = {
          id: `${id}$${projectEnv[j]}`,
          topic: projectEnv[j],
          parentid: _id,
          props: {
            project_id: id,
            project_name: name,
            level: 3,
          },
          className: 'node_level3',
          ...renderEnvStyle(projectEnv[j]),
        };
        arr.push(envItem);
      }
    }
    return arr;
  };
  // 获取所有的项目。
  const getProjectList = async () => {
    try {
      const res: any = await searchApi({ showInMind: 1 });
      if (res) {
        return res;
      }
      return [];
    } catch (err) {
      console.log(err);
      return [];
    }
  };

  // const zoomIn = () => {
  //   jm.current.view.zoomIn();
  // };
  // const zoomOut = () => {
  //   jm.current.view.zoomOut();
  // };
  // const getSelectNode = () => {
  //   const node = jms.get_selected_node();
  // };

  // 4、生成级联关系
  const renderCascadeRelation = (data) => {
    const res: any = [];
    for (let i = 0; i < data.length; i += 1) {
      const { env: envi, project_id, branch, developer, _id, story_name, story_id } = data[i] as storyWithProjectItem;
      if (project_id && envi) {
        // {"id":"open2", "parentid":"open", "topic":"BSD License"},
        res.push({
          id: _id,
          parentid: data[i].parentid ? data[i].parentid : `${project_id}$${envi}`,
          topic: branch,
          props: {
            ...data[i],
            level: 4,
          },
          className: 'node_level3',
          ...branchStyle,
        });
      }
      if (developer) {
        const developerStr = developer.toString();
        res.push({
          id: `${_id}$${developerStr}`,
          parentid: _id,
          topic: developerStr,
          ...nameStyle,
        });
        if (story_name) {
          res.push({
            id: `${_id}$${story_name}`,
            parentid: `${_id}$${developerStr}`,
            topic: story_name,
            ...storyStyle,
            story_id,
          });
        }
      } else if (story_name) {
        res.push({
          id: `${_id}$${story_name}`,
          parentid: `${_id}`,
          topic: story_name,
          ...storyStyle,
          story_id,
        });
      }
    }
    return res;
  };

  // 获取脑图数据
  const handleGetEnv = async () => {
    try {
      const res = await getListApi();
      if (res) {
        return res;
      }
      return [];
    } catch (err) {
      console.log(err);
      return [];
    }
  };

  const handleData = async () => {
    // 1、获取所有的项目
    const projectRes = await getProjectList();
    projectRes.sort((a, b) => a.name?.localeCompare(b.name));
    const nameArr = projectRes.map((item) => ({ label: item.name, value: item.name }));
    setProjectOption(nameArr);
    const curProjectEnv = envs2(projectRes);
    // 2、所有需求使用 项目、环境、分支 数据
    const storyRes = await handleGetEnv();
    const branchList = renderCascadeRelation(storyRes);
    // 3、生成结构
    treeData.current = [].concat(curProjectEnv, branchList);
    // 4、生成树
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    writeMind(renderMind(treeData.current));
  };

  const addNode = (snode, el) => {
    el.handleOpen(snode);
  };

  const inMergeBranch = async (snode) => {
    const { parentid } = snode.data.props;
    setSelectNode(snode);
    try {
      const res: any = await getMergeBranchListApi({ parentid });
      if (res) {
        if (res && res.length) {
          setOpenDialog(true);
          setMergeBranchList(res || []);
        } else {
          message.warning('没有可用的合并分支');
        }
      }
    } catch (err) {
      console.log(err);
      message.warning('没有可用的合并分支');
    }
  };
  const handleInMergeBranch = async () => {
    if (!mergeBranch) return;
    const { _id } = selectNode.data.props;
    try {
      const res = await moveBranchApi({ parentid: mergeBranch, _id });
      if (res) {
        setOpenDialog(false);
        setMergeBranch('');
        setSelectNode(undefined);
        jm.current.move_node(selectNode, '_last_', mergeBranch);
        jm.current.select_clear();
      } else {
        message.warning('移动失败');
      }
    } catch (err) {
      console.log(err);
      message.warning('移动失败');
    }
  };
  const changeMergeBranch = async (snode) => {
    setSelectNode(snode);
    const { parentid } = snode.parent.data.props;
    try {
      const res: any = await getMergeBranchListApi({ parentid });
      if (res && res.length) {
        setOpenDialog(true);
        setMergeBranchList(res || []);
      } else {
        message.warning('没有可用的合并分支');
      }
    } catch (err) {
      console.log(err);
      message.warning('没有可用的合并分支');
    }
  };
  const removeMergeBranch = async (snode) => {
    const childrenIds = snode.children.map((item) => item.id);
    const res = await deleteMergeBranchApi({
      _id: snode.data.props._id,
      children: childrenIds,
      parentid: snode.data.props.parentid,
    });
    if (res) {
      jm.current.remove_current_node(snode);
      jm.current.select_clear();
    }
  };
  const outMergeBranch = async (snode) => {
    const copy = snode;
    const { parentid } = snode.parent.data.props;
    const _id = snode.id;
    try {
      const res = await moveBranchApi({ parentid, _id });
      if (res) {
        jm.current.move_node(snode, '_last_', parentid);
        jm.current.select_clear();
        copy.data.props.parentid = parentid;
      }
    } catch (err) {
      console.log(err);
      message.warning('没有合并分支');
    }
  };
  // 生成树形
  const writeMind = (tD) => {
    if (!jm.current) {
      // eslint-disable-next-line new-cap
      jm.current = new jsMind(options());
      jm.current.remove_current_node = remove_current_node;
    }
    // 让 jm 显示这个 mind 即可
    jm.current.show(tD);
    if (typeof window !== 'undefined') {
      window.jsmind = jsMind;
      m = mergeBranchModal?.current;
      menuDefine(window, 'jsmind', {
        addNode(node) {
          addNode(node, m);
        },
        inMergeBranch,
        removeMergeBranch,
        outMergeBranch,
        changeMergeBranch,
      });
    }
  };

  // 筛选
  const handleMindFilter = (data) => {
    const { project, env: e } = data;
    if (e === 'all' && project === 'all') {
      writeMind(renderMind(treeData.current));
    } else if (e === 'all') {
      const d = treeData.current.filter((item) => item?.props?.level !== 2 || item.topic === project);
      writeMind(renderMind(d));
    } else if (project === 'all') {
      const d = treeData.current.filter((item) => item?.props?.level !== 3 || item.topic === e);
      writeMind(renderMind(d));
    } else {
      const d = treeData.current.filter((item) => (item?.props?.level !== 2 || item.topic === project) && (item?.props?.level !== 3 || item.topic === e));
      writeMind(renderMind(d));
    }
    // writeMind(renderMind(treeData.current));
  };

  // 重置筛选
  const handleMindFilterRest = () => {
    writeMind(renderMind(treeData.current));
  };

  useEffect(() => {
    handleData();
  }, []);

  const handleClick = async (e) => {
    const jms = jm.current;
    const selected = jms.get_selected_node();
    if (!selected) return;
    if (e.target.nodeName === 'MENU-ITEM') return;
    const bg = selected.data['background-color'];
    const color = selected.data['foreground-color'];
    jms.set_node_color(selected.id, bg, color);
    const { topic } = selected;
    // 只有环境可以点击，跳转到jenkins
    if (selected.data.props && selected.data.props.level === 3) {
      const { project_name } = selected.data.props;
      const res: any = await getSystemApi({ gitlabName: project_name, env: topic });
      if (res && res.length) {
        const url = res[0].jenkinsUrl;
        window.open(url);
      }
    }
    if (selected.data.story_id) {
      const url = `${tapdUrl}${String(selected.data.story_id)}`;
      window.open(url);
    }
  };

  // 创建合并分支回调
  const handleCallback = (curNode, newNode) => {
    // 添加新分支
    jm.current.add_node(curNode, newNode._id, newNode.branch, { props: { ...newNode, level: 4 }, ...branchStyle });
    jm.current.select_clear();
  };

  // const handleOnline = async () => {
  //   const res = await axios.post('/api/mind/delete', { id: 'c60eeefc-319c-456d-86b1-9810a742b6e2' });
  // };

  return (
    <div>
      {/* <div onClick={() => zoomIn()}>放大</div>
      <div onClick={() => zoomOut()}>缩小</div>
      <div onClick={() => getSelectNode()}>获取选中的节点</div> */}
      <PageTitle title="环境使用记录" />
      <Search envs={env} projects={projectOption} handleMindFilter={handleMindFilter} handleMindFilterRest={handleMindFilterRest} />
      <div>
        <div
          id="jsmind_container"
          style={{ flex: 1, height }}
          onClick={(e) => {
            handleClick(e);
          }}
        ></div>
        {/* <div style={{ width: '340px', padding: '20px' }}>
          <Button
            disabled={!node.length}
            style={{ marginBottom: '20px' }}
            type="primary"
            onClick={() => {
              mergeBranchModal?.current?.handleOpen();
            }}
          >
            创建合并分支
          </Button>
          <div>
            已选中的分支：
            {node.map((item) => (
              <p key={item.id}>{item.topic}</p>
            ))}
          </div>
        </div> */}
      </div>
      {/* <Button
        onClick={() => {
          handleOnline();
        }}
      >
        测试需求上线回调
      </Button> */}
      <MergeBranch ref={mergeBranchModal} handleCallback={handleCallback} />
      <MyModal
        destroyOnClose
        title="选择合并分支"
        open={openDialog}
        onOk={() => {
          handleInMergeBranch();
        }}
        onCancel={() => {
          setOpenDialog(false);
        }}
      >
        <Radio.Group
          onChange={(e) => {
            setMergeBranch(e.target.value);
          }}
          value={mergeBranch}
        >
          <Space direction="vertical">
            {mergeBranchList.map((item: any) => (
              <Radio key={item._id} value={item._id}>
                {item.branch}
              </Radio>
            ))}
          </Space>
        </Radio.Group>
      </MyModal>
    </div>
  );
};

export default Mind;
